package com.itcs.app.pay.swiftpass.callback;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itcs.app.pay.constants.CallbackPayStatus;
import com.itcs.app.pay.model.QrcodeCallBackData;
import com.itcs.app.pay.nowpay.constants.PayChannelType;
import com.itcs.app.pay.service.PayService;
import com.itcs.app.pay.swiftpass.SwiftpassPayPlatform;
import com.itcs.app.pay.swiftpass.properties.SwiftpassProperties;
import com.itcs.app.pay.swiftpass.util.PaymentKit;
import com.itcs.app.util.XmlJsonUtils;
import com.itcs.box.util.LogUtils;

/**
 * 回调API
 */
@Controller
@RequestMapping("/swiftpassCallBack")
public class SwiftpassCallBackApi {
	private Log logger = LogFactory.getLog(getClass());

	@Autowired
	private SwiftpassProperties config;
	
	@Autowired
	private PayService payService;

	/**
	 * 威富通支付,主扫回调 商户后台通知URL
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "achBackNotify")
	public void achBackNotify(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		try {
			// 获取通知数据需要从body中流式读取
			BufferedReader reader = request.getReader();
			StringBuilder reportBuilder = new StringBuilder();
			String tempStr = "";
			while ((tempStr = reader.readLine()) != null) {
				reportBuilder.append(tempStr);
			}
			String reportContent = reportBuilder.toString();
			String xml2json = XmlJsonUtils.xml2json(reportContent);
			JSONObject jsonObject = JSON.parseObject(xml2json);
			logger.info(LogUtils.build("achBackNotify", "威富通支付回调", "订单号:" + jsonObject.getString("out_trade_no"),
					jsonObject.toJSONString()));
			
			String payChannelType = PayChannelType.WECHAT_PAY;
			if ("pay.alipay.jspay".equals(jsonObject.getString("trade_type"))) {//pay.weixin.jspay,pay.alipay.jspay
				payChannelType = PayChannelType.ALIPAY;
			}

			// 去除签名值
			Map<String, String> map = jsonObject.toJavaObject(Map.class);//威富通
			String signature = jsonObject.getString("sign");//威富通返回的签名
			map.remove("sign");//威富通
			//被扫回调
			logger.info(LogUtils.build("achBackNotify", "威富通支付主扫回调", "订单号:" + jsonObject.getString("out_trade_no")));
			// 验证签名
			boolean isValidSignature = false;
			if (PayChannelType.WECHAT_PAY.equals(payChannelType)) {
				isValidSignature = signature.equals(PaymentKit.createSign(map, config.getWxResKey()));//微信签名
			}else if(PayChannelType.ALIPAY.equals(payChannelType)) {
				isValidSignature = signature.equals(PaymentKit.createSign(map, config.getAliResKey()));//支付宝签名
			}
			if (!isValidSignature) {
				response.getOutputStream().write("success=N".getBytes());
				logger.error(LogUtils.build("achBackNotify", "威富通支付主扫回调", "签名验证失败", jsonObject.toJSONString()));
				return;
			}

			String payChannelCode = PayChannelType.payChannelType2Code(payChannelType);

			String transNo = jsonObject.getString("out_trade_no");
			String payStatus = CallbackPayStatus.PAY_FAILED;
			if ("0".equals(jsonObject.getString("pay_result"))) {
				payStatus = CallbackPayStatus.PAY_SUCCESS;
			}
			String platformOrderNo = jsonObject.getString("transaction_id");
			String channelOrderNo = jsonObject.getString("out_transaction_id");
			
			QrcodeCallBackData qrcodeCallBackData = new QrcodeCallBackData(transNo, payStatus, platformOrderNo, channelOrderNo,
					SwiftpassPayPlatform.TYPE, payChannelCode);
			payService.qrcodeCallback(qrcodeCallBackData);
				

			response.getWriter().write("success");//返回威富通的成功标志
		} catch (Exception ex) {
			logger.error(LogUtils.build("achBackNotify", "威富通支付主扫回调", "回调处理失败," + ex.getMessage()), ex);
			response.getOutputStream().write("success=N".getBytes());
		}
	}

}
